<?php

namespace app\admin\controller;

use app\base\model\RoleUser;
use app\base\model\User;
use app\common\controller\AdminBase;
use think\Request;
use think\Config;

class Classes extends AdminBase {
  protected $model, $modelRoleUser, $modelUser;

  public function __construct(Request $request = NULL) {
    parent::__construct($request);
    $this->model = new \app\admin\model\Classes();
    $this->modelUser = new User();
  }

  public function _initialize() {
    parent::_initialize();
  }

  public function index() {
    $search = input('search/a', NULL);
    $map = [];
    if (isset($search['title'])) {
      $map['c.title'] = ['like',
                         "%$search[title]%"];
    }
    $rows = $this->model->alias('c')
      ->join('__BASE_USER__ u', 'u.id=c.teacher_uid', 'left')
      ->where($map)
      ->field('c.*,u.realname')
      ->paginate();

    $classes = $this->model->column('title', 'id');
    $classes = [0 => '-'] + $classes;

    return view('', [
      'rows'    => $rows,
      'classes' => $classes,
      'search'  => $search,
    ]);
  }

  public function add() {
    return self::edit();
  }

  public function edit() {
    $id = input('id/d', 0, 'abs');
    if (!request()->isPost()) {
      $row = ($id > 0) ? $this->model->find($id) : [];
      $teachers = $this->modelUser->getTeachers();

      return view('edit', [
        'row'      => $row,
        'teachers' => $teachers]);
    }
    $form = input('form/a', NULL, 'trim');
    $result = $this->validate($form, 'Classes');
    if (TRUE !== $result) {
      $this->error($result);
    }
    cmf_log('新增/编辑班级', $id,$form);
    $this->model->editJump($form, $id, 'index');
  }


}